<?php

namespace App\Http\Controllers\Wechat;


use App\Models\Wechat\Reply;
use App\Models\Wechat\Keyword;
use App\Models\Config;
use EasyWeChat\Kernel\Messages\Transfer;

class TextController 
{
    //消息对象
	var $message;
    //全局app对象
    var $app;
    //回复对象
    var $reply;

	public function __construct($message,$app){
		$this->message = $message;
        $this->app = $app;
	}

    public function entrance(){
    	$keyword = $this->getKeyword();
    	if(!$keyword){
    		return $this->getDefaultReply();
    	}else{
            return $this->getKeywordReply($keyword);
        }
    }

    /**
     * 获取关键词回复
     * @return [type] [description]
     */
    public function getKeyword(){
    	$content = $this->message['Content'];
    	return Keyword::where('keyword',$content)->first();
    }

    /**
     * 获取默认回复
     * @return [type] [description]
     */
    public function getDefaultReply(){
    	$reply = new Reply();
    	$config = new Config();

        //客服开启,消息转入客服
        $customer = $config->cacheFindByKey($reply->staticName['customer_switch']);
        if($customer && $customer->switch){
            return new Transfer();
        }

    	$config = $config->cacheFindByKey($reply->staticName['default']);
    	//未有默认回复,返回空
    	if(!$config){
    		return '';
    	}
    	$config->vue = json_decode($config->vue);
        $replyController = new ReplyController($this->app,$config->vue->wechat_image_id,$config->vue->wechat_mpnews_id,$config->vue->wechat_text_id);
    	return $replyController->entrance();
    }

    /**
     * 关键词回复
     * @return [type] [description]
     */
    public function getKeywordReply($keyword){
        $reply = new Reply();
        $reply = $reply->cacheFindFromKeyword($keyword->id);
        $replyController = new ReplyController($this->app,$reply->wechat_image_id,$reply->wechat_mpnews_id,$reply->wechat_text_id);
        return $replyController->entrance();
    }
}
